﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.IO;
using System.Text;
using System.Web;

namespace Library
{
    public static class LogHelper
    {
        private static readonly string LogDirectory = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\" + Settings.LogDirectory + "\\";

        public static void Write(string content)
        {
            var filename = LogDirectory + DateTime.Today.ToString("yyyy-MM-dd") + ".log";
            try
            {
                StreamWriter sw = File.Exists(filename) ? new StreamWriter(filename, true, Encoding.UTF8) : new StreamWriter(filename, false, Encoding.UTF8);
                 
                sw.WriteLine("----- {0} -------------------------------------------", DateTime.Now);
                sw.WriteLine("[{0}]", HttpContext.Current.Request.Url.PathAndQuery);
                sw.WriteLine(content);
                sw.WriteLine("--------------------------------------------------------------------------------------\r\n\r\n\r\n");
                sw.Close();
            }
            catch (Exception e)
            {
                throw;
            }
        }

        public static void Write(Exception ex)
        {
            var asEx = ex as DbEntityValidationException;
            if (asEx != null)
            {
                var fEx = new FormattedDbEntityValidationException(asEx);
                Write(fEx.Message + "\r\n" + fEx.StackTrace);
            }
            else
            {
                Write(ex.Message + "\r\n" + ex.StackTrace);
                var innerEx = ex.InnerException;
                while (innerEx != null)
                {
                    Write(innerEx.Message + "\r\n" + innerEx.StackTrace);
                    innerEx = innerEx.InnerException;
                }
            }
        }

        public static void Write(IEnumerable<string> lines)
        {
            var sb = new StringBuilder();
            foreach (var line in lines)
            {
                sb.AppendLine(line);
            }
            Write(sb.ToString());
        }
    }
}
